<?php
/**
* 员工 自助服务
* hs_hr_employee_workgroup 员工班次表 
* hs_hr_emp_attendance "考勤记录表"
* hs_hr_emp_attendance_sp "特殊考勤表" 
* hs_hr_workgroup 员工排版表 
* hs_hr_users 用户表 
* Power by kaysonzhang 2012/5/13
**/

require_once ROOT_PATH . '/lib/confs/Conf.php';
require_once ROOT_PATH . '/lib/confs/sysConf.php';
require_once ROOT_PATH . '/lib/dao/DMLFunctions.php';
require_once ROOT_PATH . '/lib/dao/SQLQBuilder.php';

require_once ROOT_PATH . '/lib/models/time/Timesheet.php';
require_once ROOT_PATH . '/lib/models/time/TimeEvent.php';
require_once ROOT_PATH . '/lib/models/time/ProjectReport.php';
require_once ROOT_PATH . '/lib/common/TemplateMerger.php';

class SelfServiceController extends Base {
	
	private $employee_id;
	private $db;
	public $emp_number;
	private $userId;
	
	public function __construct(){
		include (ROOT_PATH . '/customConfig/attendance.config.php');
		$this->AttendanceCache = $_CfgAttendance;
		$this->db = new DMLFunctions ();
		$this->emp_number  = $_SESSION['empID'];
		$this->userId = $_SESSION['user'];
		$this->GetUserName();
	}
	
	/* 获取用户帐号 */
	private function GetUserName() {
		$sql = "select user_name from hs_hr_users  where id ='$this->userId'";
		$query = $this->db->executeQuery ( $sql );
		$row = mysql_fetch_array ( $query, MYSQL_ASSOC );
		if (is_array ( $row )) {
			$this->UserName = $row ['user_name'];
		} else {
			$this->_redirect( " 读取用户信息出错啦");
			exit;
		}
	
	}
	
	/* 获取管理权限 */
	private function GetPermissions() {
		
		$l_sql = "SELECT count(*) as l FROM `hs_hr_workgroup` WHERE `group_leader` = '{$this->UserName}'";
		$l_query = $this->db->executeQuery ( $l_sql );
		$l_row = mysql_fetch_array ( $l_query, MYSQL_ASSOC );
		$l_reslut = $l_row ['l'];
		
		$m_sql = "SELECT count(*) as m FROM `hs_hr_workgroup` WHERE `manager` ='{$this->UserName}'";
		$m_query = $this->db->executeQuery ( $m_sql );
		$m_row = mysql_fetch_array ( $m_query, MYSQL_ASSOC );
		$m_reslut = $m_row ['m'];
		
		
		$b_sql = "SELECT count(*) as b FROM `hs_hr_workgroup` WHERE `boss` = '{$this->UserName}'";
		$b_query = $this->db->executeQuery ( $b_sql );
		$b_row = mysql_fetch_array ( $b_query, MYSQL_ASSOC );
		$b_reslut = $b_row ['b'];
		
		$permission = $l_reslut+$m_reslut+$b_reslut;
		return  $permission;

	}
	
	/*
	 * 读取年假,需要判断是否在有效期内
	 * */
	private function getResidualHours(){
		$reslut = 0;
		$EffectDate = $EndDate = time();
		$sql = "select ResidualHours,EffectDate,EndDate from hs_hr_emp_annualleave  where EmpId ='{$this->emp_number}' ";
		$query = $this->db->executeQuery ( $sql );
		$row = mysql_fetch_array ( $query, MYSQL_ASSOC );
		if (is_array ( $row )) {
			$EffectDate = strtotime($row['EffectDate']." 00:00:00");
			$EndDate = strtotime($row['EndDate']." 23:59:59");
			
			if($EffectDate < time() && time() < $EndDate){
				$reslut = $row ['ResidualHours'];
			}
		}
		$FreezeHour = $this->getFreezeHour();
		return array(
				'jiaqi'=>$reslut-$FreezeHour,
				'FreezeHour'=>$FreezeHour,
				'EffectDate'=>date('Y年m月d日',$EffectDate)." 00:00:00",
				'EndDate'=>date('Y年m月d日',$EndDate)." 23:59:59"
				);
		
	}
	
	/*
	 * 查询被冻结的年假小时数
	 * */
	private function getFreezeHour(){
		$reslut = 0;
		$sql = "select sum(hour) as hour from hs_hr_emp_attendance_sp  where TypeId =3 and EmpId ='{$this->emp_number}' and IsCheck NOT IN ('1','2')";
		$query = $this->db->executeQuery ( $sql );
		$row = mysql_fetch_array ( $query, MYSQL_ASSOC );
		if (is_array ( $row ) && $row['hour'] > 0) {
			$reslut = $row['hour'];
		}
		
		return $reslut;
	}
	
	/**
	 * 自助服务显示页面
	 **/
	public function showIndex(){
		$reslut = array();
		$sql = "select * from hs_hr_oamenu order by mid desc ";
		$query = $this->db->executeQuery ( $sql );
		while ( $row = mysql_fetch_array ( $query, MYSQL_ASSOC ) ) {
			$reslut[] = $row;
		}
		
		$records['ResidualHours'] = $this->getResidualHours();
		$records['Permissions'] = array('permiss'=>$this->GetPermissions());
		$records['list'] = $reslut;
		$records['argclass'] = $this->viewClassMembers();

		$path = "/templates/selfservice/Show_index.php";
		$template = new TemplateMerger ($records, $path );
		$template->display ();
	}
	
	
	
	/**
	 * 查询个人当月的排班安排
	 * */
	private function viewClassMembers(){
		$year = @date('Y',time());
		$month = @date('n',time());
		$mbid = $this->emp_number;
		$selsql = "select * from hs_hr_argclass_members where m_year='$year' and m_month='$month' and mbid = '$mbid'";
		$empquery = $this->db->executeQuery($selsql);
		$row = mysql_fetch_array($empquery, MYSQL_ASSOC);
		return $row;
	}
	
	/**
	 *显示或添加特别考勤单个记录 
	 **/
	public function AddSpecialAttend($Id="") {
		
		if($Id > 0) {
			$sql = "select a.Id,a.Content,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.hour,a.AddTime,a.StartTime,a.EndTime from ".
						"hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId where a.Id={$Id}";
			$query = $this->db->executeQuery($sql);
	
			$records = mysql_fetch_array($query, MYSQL_ASSOC);
			$records['TypeName'] = $this->AttendanceCache['SpecialAdType'][$records['TypeId']];
			$records['emp_name'] = $records['emp_lastname'].$records['emp_firstname'];
		
		} else {
			
			$reslut = array();
			$sql = "select emp_lastname,emp_firstname from hs_hr_employee where emp_number = '{$this->emp_number}'";
			$query = $this->db->executeQuery($sql);
			$reslut = mysql_fetch_array($query, MYSQL_ASSOC);
			$records = array();
			$records['emp_name'] = $reslut['emp_lastname'].$reslut['emp_firstname'];
			$records['ResidualHours'] = $this->getResidualHours();
		}
		
		$records['typelist'] = $this->AttendanceCache['SpecialAdType'];
		$records['emp_number']= $this->emp_number;
		$path = "/templates/selfservice/AddSpecialAttend.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	/**
	 *保存特别考勤单个记录 
	 **/
	public function SaveSpecialAttend($Id="") {
		
		$EmpId = intval($_POST["EmpId"]);
		$AdType = intval($_POST["AdType"]);
		$Content = htmlspecialchars($_POST["Content"]);
		$StartTime = strtotime($_POST["StartTime"]." ".intval($_POST["StartTime_hour"]).":".intval($_POST["StartTime_min"]).":00");
		$EndTime = strtotime($_POST["EndTime"]." ".intval($_POST["EndTime_hour"]).":".intval($_POST["EndTime_min"]).":00");
		$hour = floatval($_POST['hour']);
		$ResidualHours = $this->getResidualHours();
		
		if($StartTime > $EndTime){
			$this->redirect("开始时间不能大于结束时间", "?adcode=report&action=My&s=AddSpecialAttend");
		}
		
		if($AdType ==3 && ($ResidualHours['jiaqi']- $ResidualHours['FreezeHour']< $hour)){
			$this->redirect("你的年假不足够本次请假", "?adcode=report&action=My&s=AddSpecialAttend");
			//exit("你的年假不足够本次请假");
		}
		
		if($Id > 0) {
			$sql = "update hs_hr_emp_attendance_sp set EmpId = '{$EmpId}',TypeId = '{$AdType}',Content = '{$Content}',StartTime = '{$StartTime}',EndTime = '{$EndTime}',hour='{$hour}'  where Id={$Id}";
			
			if($this->db->executeQuery($sql)) {
				$this->redirect("保存成功", "?adcode=report&action=My&s=special");
			} else {
				$this->redirect("保存失败", "?adcode=report&action=My&s=AddSpecialAttend");
			}
		} else {
			//查询员工当前的班制的三个审批级别的人员
			$group_sql = "select group_leader,manager,boss from hs_hr_employee_workgroup as a right join hs_hr_workgroup as b on a.group_id = b.group_id where a.emp_number = '{$this->emp_number}'";
			$query = $this->db->executeQuery($group_sql);
			$result = mysql_fetch_array($query, MYSQL_ASSOC);
			
			$sql = "insert into hs_hr_emp_attendance_sp (EmpId,TypeId,Content,StartTime,EndTime,hour,AddTime, group_leader,manager,boss) values ({$EmpId},{$AdType},'{$Content}',{$StartTime},{$EndTime},'{$hour}',".time().",'".$result['group_leader']."','".$result['manager']."','".$result['boss']."')";
			
			if($this->db->executeQuery($sql)) {
				$this->redirect("添加成功", "?adcode=report&action=My&s=special");
			} else {
				$this->redirect("添加失败", "?adcode=report&action=My&s=AddSpecialAttend");
			}
		}
		
	}
	
	/*
	 *查询特殊考勤
	 * */
	public function searchSpecialAttend(){
		
		$sysConst = new sysConf ();
		$pageNO = isset ( $_POST ['pageNO'] ) ? intval ( $_POST ['pageNO'] ) : 1;
		if ($pageNO > 0) {
			$pageNO --;
			$pageNO *= $sysConst->itemsPerPage;
			$limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
		}
		
		$reslut = array ();
		$sql = "select  *  from  hs_hr_employee as a right join hs_hr_emp_attendance_sp as b on a.emp_number = b.EmpId".
			   " where a.emp_number = '{$this->emp_number}' order by b.AddTime DESC". $limit;
		
		$query = $this->db->executeQuery ( $sql );
		while ( $row = mysql_fetch_array($query,MYSQL_ASSOC) ) {
			$row ['TypeId'] = $this->AttendanceCache ['SpecialAdType'] [$row ['TypeId']];
			$reslut[] = $row;
		}
		
		$records = array ();
		$records ['list'] = $reslut;
		$records ['title'] = $title;
		$records ['pageNo'] = $pageNO;
		$records ['Allcount'] = $Allcount ['allcount'];
		$records ['TypeId'] = $TypeId;
		
		$path = "/templates/selfservice/Show_Approval.php";
		$template = new TemplateMerger ( $records, $path );
		$template->display ();
		 
	}
	
	/**
	 *删除特殊考勤数据
	 **/
	public function deleteSpecialAttend($Id=""){
		$url = "?adcode=report&action=My&s=special";
		if(empty($Id)){
			$this->redirect("缺少id参数", $url);
		}
	
		$sql = "delete from hs_hr_emp_attendance_sp where Id='{$Id}' and EmpId='{$this->emp_number}'";
	
		if($this->db->executeQuery($sql)) {
			$this->redirect("删除成功", $url);
		} else {
			$this->redirect("删除失败", $url);
		}
	
	}
	
	/*
	 * 自定义oa的菜单分类
	 * 
	 * */
	private function defType(){
		$result = array();
		$sql = "select * from hs_hr_oamenu order by mid desc";
		$query = $this->db->executeQuery ( $sql );
		while ( $row = mysql_fetch_array ( $query, MYSQL_ASSOC ) ) {
			$result[$row['mid']] = $row['typename'];
		}
		return $result;
	}
	
	/*
	 *查询自定义OA数据
	 * */
	public function searchDefineAttend($TypeId = '1'){
		$AttendanceCache = $this->defType();
		
		$sysConst = new sysConf ();
		$pageNO = isset ( $_POST ['pageNO'] ) ? intval ( $_POST ['pageNO'] ) : 1;
		if ($pageNO > 0) {
			$pageNO --;
			$pageNO *= $sysConst->itemsPerPage;
			$limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
		}
		
		$title = $AttendanceCache[$TypeId];
		
		$reslut = array ();
		$sql = "select  a.emp_number,a.emp_lastname,a.emp_firstname,b.Id,b.IsCheck,b.Content,b.TypeId,b.IsAllDay,b.StartTime,".
				"b.EndTime,b.hour,b.AddTime,b.group_leader,b.manager,b.boss  from  hs_hr_employee as a left join hs_hr_oa_approval as b on a.emp_number = b.EmpId".
			   " where a.emp_number = '{$this->emp_number}' and b.TypeId = '{$TypeId}' order by b.AddTime DESC". $limit;

		$query = $this->db->executeQuery ( $sql );
		while ( $row = mysql_fetch_array($query,MYSQL_ASSOC) ) {
			$row ['TypeName'] = $AttendanceCache[$row ['TypeId']];
			$reslut[] = $row;
		}
		
		$records = array ();
		$records ['list'] = $reslut;
		$records ['title'] = $title;
		$records ['pageNo'] = $pageNO;
		$records ['Allcount'] = $Allcount ['allcount'];
		$records ['TypeId'] = $TypeId;
		
		$path = "/templates/selfservice/Show_defApproval.php";
		$template = new TemplateMerger ( $records, $path );
		$template->display ();
		 
	}
	
	/**
	 *显示或添加OA自定义数据
	 **/
	public function AddDefineAttend($Id="",$TypeId = '1') {
		$AttendanceCache = $this->defType();
		if($Id > 0) {
			$sql = "select a.Id,a.Content,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.hour,a.AddTime,a.StartTime,a.EndTime from hs_hr_oa_approval a left join hs_hr_employee b on b.emp_number = a.EmpId where a.Id={$Id}";
			$query = $this->db->executeQuery($sql);
			
			$records = mysql_fetch_array($query, MYSQL_ASSOC);
			$records['TypeName'] = $AttendanceCache[$records['TypeId']];
			$records['emp_name'] = $records['emp_lastname'].$records['emp_firstname'];
		
		} else {
			
			$reslut = array();
			$sql = "select emp_lastname,emp_firstname from hs_hr_employee where emp_number = '{$this->emp_number}'";
			$query = $this->db->executeQuery($sql);
			$reslut = mysql_fetch_array($query, MYSQL_ASSOC);
			$records = array();
			$records['emp_name'] = $reslut['emp_lastname'].$reslut['emp_firstname'];
		}

		$records['title'] = $AttendanceCache[$TypeId];
		$records['TypeId'] =  $TypeId;
		$records['typelist'] =  $AttendanceCache;
		$records['emp_number']= $this->emp_number;
		$path = "/templates/selfservice/AddDefineAttend.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	/**
	 *删除OA自定义数据
	 **/
	public function deleteDefineAttend($Id="",$TypeId){
		$url = "?adcode=report&action=My&s=defApproval&TypeId={$TypeId}";
		if(empty($Id)){
			$this->redirect("缺少id参数", $url);
		}
		
		$sql = "delete from hs_hr_oa_approval where Id='{$Id}' and EmpId='{$this->emp_number}'";
		
		if($this->db->executeQuery($sql)) {
			$this->redirect("删除成功", $url);
		} else {
			$this->redirect("删除失败", $url);
		}
		
	}
	
	/**
	 *保存OA自定义数据
	 **/
	public function SaveDefineAttend($Id="") {
		
		$EmpId = intval($_POST["EmpId"]);
		$TypeId = intval($_POST["TypeId"]);
		$Content = $_POST["Content"];
		$StartTime = strtotime($_POST["StartTime"]." ".intval($_POST["StartTime_hour"]).":".intval($_POST["StartTime_min"]).":00");
		$EndTime = strtotime($_POST["EndTime"]." ".intval($_POST["EndTime_hour"]).":".intval($_POST["EndTime_min"]).":00");
		$hour = $_POST['hour'];
		
		if($StartTime > $EndTime){
			$URL = ($Id > 0) ? "&Id={$Id}" : "&TypeId={$TypeId}";
			$this->redirect("开始时间不能大于结束时间", "?adcode=report&action=AddDefineAttend&s=AddSpecialAttend".$URL);
		}
		
		if($Id > 0) {

			$sql = "update hs_hr_oa_approval set EmpId = '{$EmpId}',TypeId = '{$TypeId}',Content = '{$Content}',StartTime = '{$StartTime}',EndTime = '{$EndTime}',hour='{$hour}'  where Id={$Id}";
			
			if($this->db->executeQuery($sql)) {
				$this->redirect("保存成功", "?adcode=report&action=My&s=defApproval&TypeId={$TypeId}");
			} else {
				$this->redirect("保存失败", "?adcode=report&action=My&s=AddDefineAttend&Id={$Id}");
			}
		} else {
			//查询员工当前的班制的三个审批级别的人员
			$group_sql = "select group_leader,manager,boss from hs_hr_employee_workgroup as a right join hs_hr_workgroup as b on a.group_id = b.group_id where a.emp_number = '{$this->emp_number}'";
			$query = $this->db->executeQuery($group_sql);
			$reslut = mysql_fetch_array($query, MYSQL_ASSOC);
			
			$sql = "insert into hs_hr_oa_approval (EmpId,TypeId,Content,StartTime,EndTime,hour,AddTime,group_leader,manager,boss) values ({$EmpId},{$TypeId},'{$Content}','{$StartTime}','{$EndTime}','{$hour}',".time().",'".$reslut['group_leader']."','".$reslut['manager']."','".$reslut['boss']."')";
			
			if($this->db->executeQuery($sql)) {
				$this->redirect("添加成功", "?adcode=report&action=My&s=defApproval&TypeId={$TypeId}");
			} else {
				$this->redirect("添加失败", "?adcode=report&action=My&s=AddDefineAttend");
			}
		}
		
	}
}
?>

 